import {Subject} from 'rxjs';
import {ModelService} from './model-service';
import {ReactiveEvent} from './reactive-event';

/**
 * 由于此类使用了Object.defineProperty，所以只兼容IE9以上及现代浏览器
 */
export class Model {
  public rawData: object;
  constructor(data: object, public idProperty: string, public event: ReactiveEvent) {
    this.objectDecorate(data);
    this.rawData = data;
  }

  propDecorator(propName: string): string {
    const privatePropName = `$$__${propName}`;
    Object.defineProperty(this, privatePropName, {
      configurable: true,
      writable: true
    });
    Object.defineProperty(this, propName, {
      get(): string {
        return this[privatePropName]; // tslint:disable-line:no-invalid-this
      },
      set(value: any): void {
        if (this.event) {
          const v = {};
          v[propName] = value;
          v[this.idProperty] = this[this.idProperty];
          this.event.broadcast({name: 'change', data: v, preData: this});
        }
        this[privatePropName] = value; // tslint:disable-line:no-invalid-this
      }
    });
    return privatePropName;
  }

  objectDecorate(data: object) {
    // tslint:disable-next-line:forin
    for (const prop in data) {
      const privatePropName = this.propDecorator(prop);
      this[privatePropName] = data[prop];
    }
    return data;
  }

  getId() {
    return this.idProperty;
  }
}
